package operator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

/**
 * Created by huangxiaoli on 2019/11/27 14:28
 */
public class join {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setAppName("join")
                .setMaster("local");

        JavaSparkContext sc = new JavaSparkContext(conf);

        List<Tuple2<Integer, String>> studentList = Arrays.asList(
                new Tuple2<Integer, String>(1, "tom"),
                new Tuple2<Integer, String>(2, "jack"),
                new Tuple2<Integer, String>(3, "marry"),
                new Tuple2<Integer, String>(4, "leo"));

        List<Tuple2<Integer, Integer>> scoreList = Arrays.asList(
                new Tuple2<Integer, Integer>(1, 78),
                new Tuple2<Integer, Integer>(2, 87),
                new Tuple2<Integer, Integer>(3, 89),
                new Tuple2<Integer, Integer>(4, 98));

        //并行化两个RDD
        JavaPairRDD<Integer, String> students = sc.parallelizePairs(studentList);;
        JavaPairRDD<Integer, Integer> scores = sc.parallelizePairs(scoreList);

        //使用join算子关联两个RDD
        //join以后，会根据key进行join，并返回JavaPairRDD
        //JavaPairRDD的第一个泛型类型，之前两个JavaPairRDD的key类型，因为通过key进行join的
        //第二个泛型类型，是Tuple2<v1, v2>的类型，Tuple2的两个泛型分别为原始RDD的value的类型
        JavaPairRDD<Integer, Tuple2<String, Integer>> studentScores = students.join(scores);

        //打印
        studentScores.foreach(new VoidFunction<Tuple2<Integer,Tuple2<String,Integer>>>() {
            @Override
            public void call(Tuple2<Integer, Tuple2<String, Integer>> t)
                    throws Exception {
                System.out.println("student id:" + t._1);
                System.out.println("student name:" + t._2._1);
                System.out.println("student score:" + t._2._2);
                System.out.println("==========================");
            }
        });
        sc.close();
    }

}
